<?php

namespace App\Listeners;

use App\Events\ProfitShare;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Models\ProfitSharingAccount;
use App\Contracts\WxProfitSharing;
use App\Models\ProfitSharingReceiver;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Artisan;

class WxProfitShareOnce implements ShouldQueue
{
    /**
     * 队列连接名称
     * @var string
     */
    public $connection = 'database';

    /**
     * 队列名称
     *
     * @var string
     */
    public $queue = 'default';

    /**
     * 延迟处理时间 秒
     *
     * @var int
     */
    public $delay = 60;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  ProfitShare  $event
     * @return void
     */
    public function handle(ProfitShare $event)
    {
        $notifyData = $event->notifyData;
        Log::info('接受到的数据::'.json_encode($notifyData,JSON_UNESCAPED_UNICODE));
        $subAppId = isset($notifyData['sub_appid']) ? $notifyData['sub_appid'] : $notifyData['appid'];
        $subMchId = isset($notifyData['sub_mch_id']) ? $notifyData['sub_mch_id'] : $notifyData['mch_id'];

        // 获取分账接收方
        $wxProfitSharingAccount = ProfitSharingAccount::where('sub_appid', $subAppId)->where('sub_mchid', $subMchId)->first();
        Log::info('WxProfitShareOnce Listener------begin');
        
        //组装config
        $config = [
            'appCertPem'=>$wxProfitSharingAccount->app_certpem,
            'appKeyPem'=>$wxProfitSharingAccount->app_keypem,
            'appId' => $wxProfitSharingAccount->sub_appid,
            'mchId' => $wxProfitSharingAccount->sub_mchid,
            'md5Key' => $wxProfitSharingAccount->md5key,
            'is_mch' => $wxProfitSharingAccount->is_mch,
        ];
        Log::info('config ::' .json_encode($config));
        
        if(!empty($wxProfitSharingAccount))
        {
            $wxProfitSharingReceivers = ProfitSharingReceiver::where('profit_sharing_account_id',$wxProfitSharingAccount->id)->get();
            Log::info($wxProfitSharingReceivers);
            Log::info('WxProfitShareOnce Listener------end');

            if(!empty($wxProfitSharingReceivers))
            {
                // 组合分账接收方
                $finalReceivers = array();
                $receivers = array();

                // 组合分账接收方
                foreach ($wxProfitSharingReceivers as $wxProfitSharingReceiver)
                {
                    $receiversTmp = array();
                    $receiversTmp['type'] = $wxProfitSharingReceiver['type'];
                    $receiversTmp['account'] = $wxProfitSharingReceiver['account'];
                    $receiversTmp['amount'] = intval(bcmul(bcdiv($wxProfitSharingReceiver['amount'],100,2), $notifyData['total_fee']));// 单位：分。且是整型，不能是字符串
                    $receiversTmp['description'] = $wxProfitSharingReceiver['desc'];

                    $receivers[] = $receiversTmp;
                }

                $finalReceivers[] = [
                    'profit_sharing_order_id'=>$notifyData['transaction_id'].'_'.$notifyData['out_trade_no'],
                    'accounts'=>$receivers,
                ];

                $channel = $subAppId.'_'.$subMchId;// 渠道标志
                $transId = $notifyData['transaction_id'];// 微信支付商户号
                
                $profitSharing = new WxProfitSharing($config);
                $profitSharing->req($channel, $transId, $subAppId, $subMchId, $finalReceivers);
                $profitSharing->profitSharing();
            }
        }
    }
}
